package pl.edu.pw.stud.ltrzaska.test;

import static org.junit.Assert.assertTrue;

import java.io.File;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.log4j.Logger;
import org.junit.Test;

import pl.edu.pw.stud.ltrzaska.exception.FilesysPolicyException;
import pl.edu.pw.stud.ltrzaska.filesystem.VirtualFsReader;
import pl.edu.pw.stud.ltrzaska.logic.FsEquivalentsFinder;
import pl.edu.pw.stud.ltrzaska.logic.FsObjectEquivalent;
import pl.edu.pw.stud.ltrzaska.logic.PolicyLoader;
import pl.edu.pw.stud.ltrzaska.policy.entity.Policy;

public class TraverseFilesystemTestCase {
	private static final Logger LOGGER = Logger.getLogger(LoadPolicyTestCase.class);

	@Test
	public void findEquivalents() throws FilesysPolicyException, FileSystemException {
		LOGGER.debug("Running test " + LoadPolicyTestCase.class.getName());
		String curDir = System.getProperty("user.dir");

		String policyFilesystem = new StringBuffer(curDir).append("/tests/test-filesystem/projekt/").toString();
		File policyFile = new File(curDir, "/tests/test-filesystem/policy-1.xml");

		findEquivalentsTasks(curDir, policyFilesystem);
	}

	@Test
	public void findEquivalentsInZipFilesystem() throws FilesysPolicyException, FileSystemException {
		LOGGER.debug("Running test " + LoadPolicyTestCase.class.getName());
		String curDir = System.getProperty("user.dir");
		String policyFilesystem = new StringBuffer("zip://").append(curDir).append("/tests/test-filesystem/projekt-arch.zip").toString();

		findEquivalentsTasks(curDir, policyFilesystem);
	}

	private void findEquivalentsTasks(String curDir, String policyFilesystem) throws FilesysPolicyException, FileSystemException {
		File policyFile = new File(curDir, "/tests/test-filesystem/policy-1.xml");

		PolicyLoader pl = new PolicyLoader(policyFile);
		Policy policy = pl.getPolicy();

		VirtualFsReader fsReader = new VirtualFsReader(policyFilesystem);
		FileObject filesysEntry = null;
		filesysEntry = fsReader.resolve();

		FsEquivalentsFinder fsEquivalentFinder = new FsEquivalentsFinder(policy, filesysEntry);
		fsEquivalentFinder.findEquivalents();

		Map<String, LinkedList<FsObjectEquivalent>> eqs = fsEquivalentFinder.getEquivalents();
		Set<Entry<String, LinkedList<FsObjectEquivalent>>> eqsSet = eqs.entrySet();

		assertTrue(eqs.size() == 12);
		assertTrue(eqs.containsKey("aut-glow"));
	}
}
